package cn.idongjia.task.provider.init;

import cn.idongjia.task.common.constant.Excuters;
import cn.idongjia.task.common.siginal.Stopable;
import cn.idongjia.task.common.task.JobToTask;
import cn.idongjia.task.common.task.Task;
import cn.idongjia.task.common.util.TimeUtil;
import cn.idongjia.task.provider.common.ITaskProvider;
import cn.idongjia.task.provider.common.JobFinishHandler;
import cn.idongjia.task.provider.config.TaskProviderConfig;
import com.lts.core.domain.Job;
import com.lts.jobclient.JobClient;
import org.apache.log4j.Logger;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by renxianlong on 16/4/7.
 */
public class TaskProvider extends TaskProviderConfig implements Stopable, ITaskProvider {
    private JobClient delegate;

    private Logger logger = Logger.getLogger(TaskProvider.class);

//    private JobFinishHandler jobFinishHandler;


    public TaskProvider(){

    }

    public TaskProvider(TaskProviderConfig config){
        initProvider(config);
    }

    public void initProvider(TaskProviderConfig config){
        delegate = new JobClient();
        delegate.setClusterName(config.getClusterName());
        delegate.setRegistryAddress(config.getRegistAddr());
        delegate.setNodeGroup(config.getTaskProviderGroup());
        delegate.setIdentity(config.getTaskProviderName());
//        jobFinishHandler = new JobFinishHandler();
//        delegate.setJobFinishedHandler(jobFinishHandler);
//        jobFinishHandler.registHandler(config.getHandlerMap());
    }

    public void init(){
        initProvider(this);
        start();
    }

    public void start(){
        delegate.start();
    }

    @Override
    public void stop(){
        delegate.stop();
    }

//    public JobFinishHandler getJobFinishHandler() {
//        return jobFinishHandler;
//    }
//
//    public void setJobFinishHandler(JobFinishHandler jobFinishHandler) {
//        this.jobFinishHandler = jobFinishHandler;
//    }

    public void submitTask(Task task){
        logger.info(TimeUtil.getCurrentTime() + ":提交任务" + task);
        Job job =  JobToTask.convert(task);
        delegate.submitJob(job);
    }

    @Override
    public void cancelTask(String taskId) {
        delegate.cancelJob(taskId, Excuters.DONGJIA_EXCUTER);
    }

    @Override
    public void updateTask(Task task) {
        logger.info(TimeUtil.getCurrentTime() + ":更新任务" + task);
        Job job =  JobToTask.convert(task);
        delegate.submitJob(job);
    }
}
